<script lang="ts" setup>
import type { FormRulesExt } from '#/api';

import { reactive, ref, toRaw } from 'vue';

import { useFs } from '@fast-crud/fast-crud';

import { getValidateRulesByFs } from '#/api/common/validateByFs';
import {
  DefGenTableApi,
  DefGenTableConfig,
} from '#/api/devOperation/developer/defGenTable';
import { ActionEnum } from '#/enums/commonEnum';

import { createCrudOptions, frontRules } from '../data/crud';

defineOptions({
  name: '修改代码配置',
  inheritAttrs: false,
});

const formRef = ref();
const formState = reactive<{ batch: boolean; tableIdListRef: string[] }>({
  batch: false,
  tableIdListRef: [],
});
const buttonLoading = ref(false);
const { crudBinding, appendCrudOptions } = useFs({
  createCrudOptions,
  context: toRaw(formState),
});

async function handleSubmit() {
  buttonLoading.value = true;
  try {
    await formRef.value.submit();
  } finally {
    buttonLoading.value = false;
  }
}

const load = async (tableId: string) => {
  const tableIdList = tableId.includes(',') ? tableId.split(',') : [tableId];
  formState.tableIdListRef = tableIdList;
  formState.batch = tableIdList.length > 1;

  const record = await DefGenTableApi.detail(tableIdList[0] as string);
  formRef.value.setFormData(record, { mergeForm: false });
  const fcRef = formRef.value.getComponentRef('menuParentId');
  fcRef?.reloadDict();

  const customRules: FormRulesExt = frontRules.editForm.rules;
  const validateApi = DefGenTableConfig.Update;
  const formOptions = await getValidateRulesByFs({
    Api: validateApi,
    mode: ActionEnum.EDIT,
    customRules,
    trigger: 'change',
  });
  appendCrudOptions({ ...formOptions });
};

async function validate() {
  await formRef.value.getFormRef().validate();
}

defineExpose({ load, handleSubmit, validate });
</script>

<template>
  <FsForm ref="formRef" v-bind="crudBinding.editForm" />
</template>
